package com.sx.micowell.framework.model

import android.annotation.SuppressLint
import android.text.TextUtils
import androidx.databinding.ObservableField
import com.example.mvvm.base.vm.BaseViewModel
import com.example.mvvm.event.SingleLiveEvent
import com.example.mvvm.until.LogUtils
import com.example.mvvm.until.ToastUtils
import com.miloyu.modelnet.network.ApiResponse
import com.miloyu.modelnet.network.HttpClient
import com.miloyu.modelnet.network.tools.RxUtils
import com.sx.micowell.framework.arouth.RouteManager
import com.sx.micowell.framework.binding.BindingCommand
import com.sx.micowell.framework.binding.impl.IBindingAction

/**
 * @Author: YY
 * @Time: 2021/9/11
 * @Describe TODO
 */
class BindPhoneModel : BaseViewModel() {

    //发送验证码
    var sendCodeEvent: SingleLiveEvent<Void> = SingleLiveEvent()

    // 类型
    var type = -1

    // 手机号码
    var phoneNumber = ObservableField("")

    var openIDField = ObservableField("")

    //输入手机号
    var phoneNumberOnTextChangeCommand: BindingCommand<String> = BindingCommand { s ->
        LogUtils.d("phoneNumberOnTextChangeCommand: $s")
        phoneNumber.set(s)
    }

    // 下一步
    val nextStepOnClickCommand = BindingCommand<Any>(IBindingAction {
        if (TextUtils.isEmpty(phoneNumber.get())) {
            ToastUtils.showShort("请输入手机号")
            return@IBindingAction
        }
        sendSmsCode(0, phoneNumber.get().toString())
    })

    @SuppressLint("CheckResult")
    fun sendSmsCode(type: Int, phone: String) {
        if (type == 0 || type == -1) {
            HttpClient.instance.apiService
                .sendRegisterSms(phone)
                .doOnSubscribe { ui.showDialog() }
                .compose(RxUtils.compose())
                .subscribeWith(object : ApiResponse<Void>() {

                    override fun success(data: Void?, msg: String?) {
                        ui.hideDialog()
                        ToastUtils.showShort("$msg")
                        sendCodeEvent.call()
                    }

                    override fun onFail(e: Throwable?, errorMsg: String?) {
                        ui.hideDialog()
                        ToastUtils.showShort("$errorMsg")
                    }

                })

        } else {
            HttpClient.instance.apiService
                .sendModifySms(phone)
                .doOnSubscribe { ui.showDialog() }
                .compose(RxUtils.compose())
                .subscribeWith(object : ApiResponse<Void>() {

                    override fun success(data: Void?, msg: String?) {
                        ui.hideDialog()
                        ToastUtils.showShort("$msg")
                        sendCodeEvent.call()
                    }

                    override fun onFail(e: Throwable?, errorMsg: String?) {
                        ui.hideDialog()
                        ToastUtils.showShort("$errorMsg")
                    }

                })

        }
    }

}